package com.bcx.wind.workflow.support;

import java.util.*;

public class MessageUtil {

    /**
     * 翻译消息
     *
     * @param content  消息模板
     * @return   翻译后的消息
     */
    public static List<Map<String,String>> split(String content){
        LinkedList<Map<String,String>> contents = new LinkedList<>();
        char[] chars = content.toCharArray();
        StringBuilder builder = new StringBuilder();
        for (char c : chars) {
            String ret = builder.toString();
            if ("[".equals(String.valueOf(c))) {
                contents.addLast(Collections.singletonMap("w", ret));
                builder.delete(0, builder.length());
            } else if ("]".equals(String.valueOf(c))) {
                contents.addLast(Collections.singletonMap("k", ret));
                builder.delete(0, builder.length());
            } else {
                builder.append(c);
            }
        }
        return contents;
    }


    public static String trans(List<Map<String,String>> contentList,Map<String,String> data){
        StringBuilder builder = new StringBuilder();
        for(Map<String,String> contentMap : contentList){

            for(Map.Entry<String,String> content : contentMap.entrySet()){
                String type = content.getKey();
                String str = content.getValue();
                //转义
                str = trans(str,data);
                if("k".equals(type) && str.contains("${")){
                    continue;
                }


                builder.append(str);
            }
        }
        return builder.toString();
    }



    public static String  trans(String content,Map<String,String> data){
        String result = content;
        //转义
        for(Map.Entry<String,String> dataMap : data.entrySet()){
            String k = dataMap.getKey();
            String v = dataMap.getValue();
            result = result.replaceAll("\\$\\{"+k+"}",v);
        }
        return result;
    }

    public static void main(String[] args) {
        String s = "我是中国人，我的名字叫${name}，但是[存在许多个人${key}分开],存在太多，[背景换了吗${value}]";
        List<Map<String,String>> contentList = split(s);
        Map<String,String> data = new HashMap<>();
        data.put("name","张磊");
        data.put("key","分担");
        data.put("value","是的");
        String result = trans(contentList,data);
        System.out.println(result);
    }
}
